package com.ruoyi.mymod.service.impl;

import cn.hutool.json.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.ruoyi.mymod.service.ICheEntryService;
import com.ruoyi.mymod.service.IChickenService;
import com.ruoyi.mymod.utils.Dbutil;
import com.ruoyi.mymod.utils.Dbutil.Qp;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class CheEntryServiceImpl implements ICheEntryService {

    @Override
    public String getEntry() {
        Dbutil.R r = null;
        Qp qp = null;
        try {
            qp = new Qp();
            Object o = qp.setUsrpwd("pigpos", "pigpos").setSqlStr("select * from WX_CHK_ENTRY t order by t.opercode,t" +
                    ".entrytype,t.frequencycode,t.type,t.item,t.entryno ").select();
            r = (Dbutil.R) o;

        } finally {
            qp.closeConn();
        }
        return r.json;
    }

    @Override
    public String setEntry(String phone, String nowdate) {
        Dbutil.R r = null;
        Qp qp = null;
        String jsontable = "";
        try {
            qp = new Qp();
            Object o = qp.setUsrpwd("pigpos", "pigpos").setSqlStr("select a.*,r.chk_result from wx_chk_entry a,\n" +
                    "(\n" +
                    "select entryid, chk_result from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".frequency='day' and t.chk_date=trunc(sysdate,'dd')\n" +
                    "  union all\n" +
                    "select entryid, chk_result  from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".frequency='week' and t.chk_date=trunc(sysdate,'day')\n" +
                    "  union all\n" +
                    "select entryid, chk_result  from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".frequency='month' and t.chk_date=trunc(sysdate,'mm')\n" +
                    ") r\n" +
                    "where  a.id=r.entryid(+) order by a.opercode,a.frequencycode,a.type,a.item,a.entryno").select();
            r = (Dbutil.R) o;
            if (r.json.length() <= 2) {
                Dbutil.R select = qp.setSqlStr("select t.*,'' res from WX_CHK_ENTRY t order by t.opercode,t" +
                        ".entrytype,t" +
                        ".frequencycode,t.type,t.item,t.entryno ").select();
                jsontable = select.json;
            } else {
                jsontable = r.json;
            }

        } finally {
            qp.closeConn();
        }
        return jsontable;
    }


    @Override
    public String getOperators(String phone) {
        Dbutil.R r = null;
        Qp qp = null;
        try {
            qp = new Qp();
            Object o = qp.setUsrpwd("pigpos", "pigpos").setSqlStr("SELECT a.oper_obj,a.code FROM WX_CHK_OPERATOR a JOIN WX_USER b ON a.code = REGEXP_SUBSTR(b.permissions, '[^,]+', 1, 2) where b.phone=trim('"+phone+"')").select();
            r = (Dbutil.R) o;

        } finally {
            qp.closeConn();
        }
        return r.json;
    }


    @Override
    public String getFrequencys() {
        Dbutil.R r = null;
        Qp qp = null;
        try {
            qp = new Qp();
            Object o = qp.setUsrpwd("pigpos", "pigpos").setSqlStr("select * from WX_CHK_FREQUENCY t ").select();
            r = (Dbutil.R) o;

        } finally {
            qp.closeConn();
        }
        return r.json;
    }

    @Override
    public String getUsers() {
        Dbutil.R r = null;
        Qp qp = null;
        try {
            qp = new Qp();
            Object o = qp.setUsrpwd("pigpos", "pigpos").setSqlStr("select * from WX_USER t where  REGEXP_SUBSTR(t.permissions, '[^,]+', 1, 1)='write'").select();
            r = (Dbutil.R) o;

        } finally {
            qp.closeConn();
        }
        return r.json;
    }

    @Override
    public String addChe(String phone, String oper, String nowdate, List<String> completedayArry,
                         List<String> completeweekArry, List<String> completemonthArry, String completeString,
                         List<String> uncompletedayArry, List<String> uncompleteweekArry,
                         List<String> uncompletemonthArry) {

        Dbutil.R r = null;
        Qp qp = null;
        try {
            qp = new Qp().setUsrpwd("pigpos", "pigpos");

            //处理日被选中的
            if (completedayArry.size() > 0 && !"[]".equals(completedayArry.get(0))) {
                Qp finalQp = qp;
                String delsql =
                        "delete from WX_CHK_RECORD t where t.userphone='" + phone + "' and t.oper='" + oper + "' and " +
                                "t.frequency='day' and t.CHK_RESULT='已完成' and t.chk_date=TO_DATE('" + nowdate + "'," +
                                "'yyyy-MM-dd')";
                qp.setSqlStr(delsql).select();
                List<String> completedayArry1 = replaceBrackets(completedayArry);
                processListInChunks(completedayArry1, 50, chunk -> {
                    String y = concatenateStrings(oper, "day", phone, nowdate, "已完成", nowdate, chunk);
                    if (!"".equals(y)) {
                        String sql = "insert into WX_CHK_RECORD (id,Oper,frequency,userphone,chk_date,CHK_RESULT," +
                                "Createdate,entryid) select myseq" +
                                ".nextval id,F0 Oper,F1 frequency,F2 userphone,TO_DATE(F3,'yyyy-MM-dd'),F4 " +
                                "CHK_RESULT,TO_DATE(F5,'yyyy-MM-dd'),F6 entryid" +
                                " from table(json2tab('" + y + "')) \n";
                        finalQp.setSqlStr(sql).select();
                    }
                });
            }

            //处理周被选中的
            if (completeweekArry.size() > 0 && !"[]".equals(completeweekArry.get(0))) {
                String lastsunday = getPreviousSundayDateString(nowdate);
                Qp finalQp = qp;
                String delsql =
                        "delete from WX_CHK_RECORD t where t.userphone='" + phone + "' and t.oper='" + oper + "' and " +
                                "t.frequency='week' and t.CHK_RESULT='已完成' and t.chk_date=TO_DATE('" + lastsunday +
                                "','yyyy-MM-dd')";
                qp.setSqlStr(delsql).select();
                List<String> completeweekArry1 = replaceBrackets(completeweekArry);
                processListInChunks(completeweekArry1, 50, chunk -> {
                    String y = concatenateStrings(oper, "week", phone, lastsunday, "已完成", nowdate, chunk);
                    if (!"".equals(y)) {
                        String sql = "insert into WX_CHK_RECORD (id,Oper,frequency,userphone,chk_date,CHK_RESULT," +
                                "Createdate,entryid) select myseq" +
                                ".nextval id,F0 Oper,F1 frequency,F2 userphone,TO_DATE(F3,'yyyy-MM-dd'),F4 " +
                                "CHK_RESULT,TO_DATE(F5,'yyyy-MM-dd'),F6 entryid" +
                                " from table(json2tab('" + y + "')) \n";
                        finalQp.setSqlStr(sql).select();
                    }
                });
            }

            //处理月被选中的
            if (completemonthArry.size() > 0 && !"[]".equals(completemonthArry.get(0))) {
                String firstmonth = getMonthStartDateString(nowdate);
                Qp finalQp = qp;
                String delsql =
                        "delete from WX_CHK_RECORD t where t.userphone='" + phone + "' and t.oper='" + oper + "' and " +
                                "t.frequency='month' and t.CHK_RESULT='已完成' and t.chk_date=TO_DATE('" + firstmonth +
                                "','yyyy-MM-dd')";
                qp.setSqlStr(delsql).select();
                List<String> completemonthArry1 = replaceBrackets(completemonthArry);
                processListInChunks(completemonthArry1, 50, chunk -> {
                    String y = concatenateStrings(oper, "month", phone, firstmonth, "已完成", nowdate, chunk);
                    if (!"".equals(y)) {
                        String sql = "insert into WX_CHK_RECORD (id,Oper,frequency,userphone,chk_date,CHK_RESULT," +
                                "Createdate,entryid) select myseq" +
                                ".nextval id,F0 Oper,F1 frequency,F2 userphone,TO_DATE(F3,'yyyy-MM-dd'),F4 " +
                                "CHK_RESULT,TO_DATE(F5,'yyyy-MM-dd'),F6 entryid" +
                                "from table(json2tab('" + y + "')) \n";
                        finalQp.setSqlStr(sql).select();
                    }
                });
            }

            //处理文字条目
            if (completeString != null && !"null".equals(completeString)) {
                Gson gson = new Gson();
                Map<String, String> map = gson.fromJson(completeString, Map.class);
                // 遍历Map
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    String value = entry.getValue();
                    String[] split = value.split("/");
                    String id = split[0];
                    String result = split[1];
                    String sql = "insert into WX_CHK_RECORD (id,userphone,Oper,Entryid,CHK_RESULT,Createdate) values " +
                            "(myseq.nextval,'" + phone + "','" + oper + "'," + id + ",'" + result + "',TO_DATE('" + nowdate + "','yyyy-MM-dd'))";
                    qp.setSqlStr(sql).select();
                }
            }


            //处理天未被选中的
            if (uncompletedayArry.size() > 0 && !"[]".equals(uncompletedayArry.get(0))) {
                Qp finalQp = qp;
                String delsql =
                        "delete from WX_CHK_RECORD t where t.userphone='" + phone + "' and t.oper='" + oper + "' and " +
                                "t.frequency='day' and t.CHK_RESULT='未完成' and t.Createdate=TO_DATE('" + nowdate + "'," +
                                "'yyyy-MM-dd')";
                qp.setSqlStr(delsql).select();
                List<String> uncompletedayArry1 = replaceBrackets(uncompletedayArry);
                processListInChunks(uncompletedayArry1, 50, chunk -> {
                    String y = concatenateStrings(oper, "day", phone, nowdate, "未完成", nowdate, chunk);
                    if (!"".equals(y)) {
                        String sql = "insert into WX_CHK_RECORD (id,Oper,frequency,userphone,chk_date,CHK_RESULT," +
                                "Createdate,entryid) select myseq" +
                                ".nextval id,F0 Oper,F1 frequency,F2 userphone,TO_DATE(F3,'yyyy-MM-dd'),F4 " +
                                "CHK_RESULT,TO_DATE(F5,'yyyy-MM-dd'),F6 entryid" +
                                " from table(json2tab('" + y + "')) \n";
                        finalQp.setSqlStr(sql).select();
                    }
                });
            }

            //处理周未被选中的
            if (uncompleteweekArry.size() > 0 && !"[]".equals(uncompleteweekArry.get(0))) {
                String lastsunday = getPreviousSundayDateString(nowdate);
                Qp finalQp = qp;
                String delsql =
                        "delete from WX_CHK_RECORD t where t.userphone='" + phone + "' and t.oper='" + oper + "' and " +
                                "t.frequency='week' and t.CHK_RESULT='未完成' and t.chk_date=TO_DATE('" + lastsunday +
                                "','yyyy-MM-dd')";
                qp.setSqlStr(delsql).select();
                List<String> uncompleteweekArry1 = replaceBrackets(uncompleteweekArry);
                processListInChunks(uncompleteweekArry1, 50, chunk -> {
                    String y = concatenateStrings(oper, "week", phone, lastsunday, "未完成", nowdate, chunk);
                    if (!"".equals(y)) {
                        String sql = "insert into WX_CHK_RECORD (id,Oper,frequency,userphone,chk_date,CHK_RESULT," +
                                "Createdate,entryid) select myseq" +
                                ".nextval id,F0 Oper,F1 frequency,F2 userphone,TO_DATE(F3,'yyyy-MM-dd'),F4 " +
                                "CHK_RESULT,TO_DATE(F5,'yyyy-MM-dd'),F6 entryid" +
                                " from table(json2tab('" + y + "')) \n";
                        finalQp.setSqlStr(sql).select();
                    }
                });
            }

            //处理月未被选中的
            if (uncompletemonthArry.size() > 0 && !"[]".equals(uncompletemonthArry.get(0))) {
                String firstmonth = getMonthStartDateString(nowdate);
                Qp finalQp = qp;
                String delsql =
                        "delete from WX_CHK_RECORD t where t.userphone='" + phone + "' and t.oper='" + oper + "' and " +
                                "t.frequency='month' and t.CHK_RESULT='未完成' and t.chk_date=TO_DATE('" + firstmonth +
                                "','yyyy-MM-dd')";
                qp.setSqlStr(delsql).select();
                List<String> uncompletemonthArry1 = replaceBrackets(uncompletemonthArry);
                processListInChunks(uncompletemonthArry1, 50, chunk -> {
                    String y = concatenateStrings(oper, "month", phone, firstmonth, "未完成", nowdate, chunk);
                    if (!"".equals(y)) {
                        String sql = "insert into WX_CHK_RECORD (id,Oper,frequency,userphone,chk_date,CHK_RESULT," +
                                "Createdate,entryid) select myseq" +
                                ".nextval id,F0 Oper,F1 frequency,F2 userphone,TO_DATE(F3,'yyyy-MM-dd'),F4 " +
                                "CHK_RESULT,TO_DATE(F5,'yyyy-MM-dd'),F6 entryid" +
                                " from table(json2tab('" + y + "')) \n";
                        finalQp.setSqlStr(sql).select();
                    }
                });
            }

        } catch (Exception e) {
            return "fail";
        } finally {
            qp.closeConn();
        }
        return "success";
    }

    @Override
    public String getHasChecked(String phone, String oper, String nowdate) {
        Dbutil.R r = null;
        Qp qp = null;
        try {
            qp = new Qp();

            Object o = qp.setUsrpwd("pigpos", "pigpos").setSqlStr("select a.type,a.item,a.entry,r.chk_result,a" +
                    ".frequencycode from " +
                    "wx_chk_entry a,\n" +
                    "(\n" +
                    "select entryid, chk_result from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".chk_result!='未完成' and  t.chk_result is not null and t.frequency='day' and t.chk_date=trunc" +
                    "(sysdate,'dd')\n" +
                    "  union all\n" +
                    "select entryid, chk_result  from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".chk_result!='未完成' and t.chk_result is not null and t.frequency='week' and t.chk_date=trunc" +
                    "(sysdate,'day')\n" +
                    "  union all\n" +
                    "select entryid, chk_result  from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".chk_result!='未完成' and t.chk_result is not null and t.frequency='month' and t.chk_date=trunc" +
                    "(sysdate,'mm')\n" +
                    ") r\n" +
                    "where  a.id=r.entryid order by a.opercode,a.frequencycode,a.type,a.item,a.entryno").select();
            r = (Dbutil.R) o;

        } finally {
            qp.closeConn();
        }
        return r.json;
    }

    @Override
    public String checkByUser(String phone, String checkdate) {
        Dbutil.R r = null;
        Qp qp = null;
        try {
            qp = new Qp();
            String lastsunday = getPreviousSundayDateString(checkdate);
            String firstmonth = getMonthStartDateString(checkdate);
            Object o = qp.setUsrpwd("pigpos", "pigpos").setSqlStr("select a.frequencycode,a.type,a.entry,r" +
                    ".chk_result,a" +
                    ".item from wx_chk_entry a,\n" +
                    "(\n" +
                    "select entryid, chk_result from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".frequency='day' and t.chk_date=TO_DATE('" + checkdate + "','yyyy-MM-dd')\n" +
                    "  union all\n" +
                    "select entryid, chk_result  from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".frequency='week' and t.chk_date=TO_DATE('" + lastsunday + "','yyyy-MM-dd')\n" +
                    "  union all\n" +
                    "select entryid, chk_result  from wx_chk_record  t where t.userphone='" + phone + "' and t" +
                    ".frequency='month' and t.chk_date=TO_DATE('" + firstmonth + "','yyyy-MM-dd')\n" +
                    ") r\n" +
                    "where  a.id=r.entryid  order by a.opercode,a.frequencycode,a.type,a.item,a.entryno").select();
            r = (Dbutil.R) o;

        } finally {
            qp.closeConn();
        }
        return r.json;
    }


    //把各种参数拼接成数组
    public String concatenateStrings(String oper, String frequency, String phone, String checkdate, String res,
                                     String createdate, List<String> param6) {
        String result = param6.stream()
                .map(listElem -> "[" + oper + "," + frequency + "," + phone + "," + checkdate + "," + res + "," + createdate + "," + listElem + "]")
                .collect(Collectors.joining(","));

        return result;
    }


    @Override
    public String getPiginfo(String phone) {
        Dbutil.R r = null;
        Qp qp = null;
        try {
            qp = new Qp();
            Object o = qp.setUsrpwd("pigpos", "pigpos").setP(phone).funcP(1, "wx_chk.farminfo");
            return o.toString();

        } finally {
            qp.closeConn();
        }

    }


    @Override
    public List<String> getSowWarm(String phone) {
        Dbutil.R r = null;
        Qp qp = null;
        List<String> warmlist = new ArrayList<>();
        try {
            qp = new Qp();
            Object o = qp.setUsrpwd("pigpos", "pigpos").setSqlStr("select t.org_code,t.farm_org from WX_CHK_USER_FARM" +
                    " t,sf_ai_sow_daily s where t.org_code=s.org_code and t.farm_org=s.farm_org and t" +
                    ".phone='" + phone + "' group by  t.org_code,t.farm_org\n").select();

            r = (Dbutil.R) o;
            String json = r.json;
            JSONArray jsonArray = new JSONArray(json);
            String[][] stringArray = new String[jsonArray.size()][];
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONArray innerArray = jsonArray.getJSONArray(i);
                stringArray[i] = new String[innerArray.size()];
                for (int j = 0; j < innerArray.size(); j++) {
                    stringArray[i][j] = innerArray.getStr(j);
                }
            }
            for (int i = 0; i < stringArray.length; i++) {
                warmlist.add(qp.setP(stringArray[i][0], stringArray[i][1]).funcP(1, "wx_chk_ext.sowwarn").toString());
            }

            return warmlist;
        } finally {
            qp.closeConn();
        }

    }



    public void processListInChunks(List<String> list, int chunkSize, Consumer<List<String>> chunkProcessor) {
        int listSize = list.size();
        for (int i = 0; i < listSize; i += chunkSize) {
            int endIndex = Math.min(i + chunkSize, listSize);
            List<String> chunk = list.subList(i, endIndex);
            chunkProcessor.accept(new ArrayList<>(chunk)); // 创建一个新列表以避免修改原始列表的子列表
        }
    }


    //创建上周日的字符串
    public String getPreviousSundayDateString(String todayDateString) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 将字符串转换为 LocalDate 对象
        LocalDate todayDate = LocalDate.parse(todayDateString, formatter);

        // 获取上一个周日
        LocalDate previousSunday = todayDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));

        // 将 LocalDate 对象转换回字符串
        return previousSunday.format(formatter);
    }

    //获取月初字符串
    public String getMonthStartDateString(String todayDateString) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 将字符串转换为 LocalDate 对象
        LocalDate todayDate = LocalDate.parse(todayDateString, formatter);

        // 获取月初日期（即当月的第一天）
        LocalDate monthStart = todayDate.withDayOfMonth(1);

        // 将 LocalDate 对象转换回字符串
        return monthStart.format(formatter);
    }

    //过滤数组
    public List<String> replaceBrackets(List<String> inputList) {
        // 创建一个新的List来存储替换后的字符串
        List<String> resultList = new ArrayList<>();

        // 遍历输入List中的每一个字符串
        for (String str : inputList) {
            // 使用String的replace方法替换掉[]符号
            String replacedStr = str.replace("[", "").replace("]", "");
            // 将替换后的字符串添加到结果List中
            resultList.add(replacedStr);
        }

        // 返回结果List
        return resultList;
    }


}
